//
//  String-base64.swift
//  Pods
//
//  Created by zhu xietong on 2017/8/9.
//
//

import Foundation
import CommonCrypto

extension String {
    public var MD5:String {
            let utf8 = cString(using: .utf8)
            var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
            CC_MD5(utf8, CC_LONG(utf8!.count - 1), &digest)
            return digest.reduce("") { $0 + String(format:"%02X", $1) }
    }
    
    
    //Encode base64
    public func base64Encoded() -> String {
        let plainData = self.data(using: String.Encoding.utf8)
        let base64String = plainData?.base64EncodedString(options: [])
        return base64String!
    }
    
    //Decode base64
    public func base64Decoded() -> String {
        let decodedData = Data(base64Encoded: self, options: [])
        let decodedString = NSString(data: decodedData!, encoding: String.Encoding.utf8.rawValue)
        return decodedString! as String
    }
}
